package com.laisheng.interview.service.impl;

import com.laisheng.interview.mapper.ResumeFileMapper;
import com.laisheng.interview.model.ResumeFile;
import com.laisheng.interview.service.ResumeFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * 简历文件服务实现类，处理简历文件的上传、下载、查询和删除等操作
 */
@Service
public class ResumeFileServiceImpl implements ResumeFileService {
    @Autowired
    private ResumeFileMapper resumeFileMapper;

    @Value("${resume.upload.path:uploads/resumes}")
    private String uploadPath;  // 简历上传路径，可通过配置文件自定义

    /**
     * 上传简历文件
     * @param file 上传的简历文件（PDF格式）
     * @param accountingInfoId 关联的面试者ID
     * @return 包含文件信息的ResumeFile对象
     * @throws Exception 上传过程中发生的异常（文件读写错误等）
     */
    @Override
    public ResumeFile uploadResume(MultipartFile file, Long accountingInfoId) throws Exception {
        // 创建上传目录
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        // 生成唯一文件名
        String originalFileName = file.getOriginalFilename();
        String fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + fileExtension;
        
        // 保存文件
        Path filePath = Paths.get(uploadPath, fileName);
        Files.copy(file.getInputStream(), filePath);

        // 保存文件信息到数据库
        ResumeFile resumeFile = new ResumeFile();
        resumeFile.setFileName(fileName);
        resumeFile.setOriginalFileName(originalFileName);
        resumeFile.setFilePath(filePath.toString());
        resumeFile.setFileType(file.getContentType());
        resumeFile.setFileSize(file.getSize());
        resumeFile.setAccountingInfoId(accountingInfoId);
        resumeFile.setUploadTime(LocalDateTime.now());
        resumeFile.setUploadStatus("success");

        resumeFileMapper.insert(resumeFile);
        return resumeFile;
    }

    /**
     * 根据面试者ID查询简历文件
     * @param accountingInfoId 面试者ID
     * @return 简历文件信息，不存在则返回null
     */
    @Override
    public ResumeFile getByAccountingInfoId(Long accountingInfoId) {
        return resumeFileMapper.getByAccountingInfoId(accountingInfoId);
    }

    @Override
    public List<ResumeFile> getAllResumeFiles() {
        return resumeFileMapper.getAllResumeFiles();
    }

    @Override
    public ResumeFile getById(Long id) {
        return resumeFileMapper.getById(id);
    }

    @Override
    public void deleteById(Long id) {
        ResumeFile resumeFile = getById(id);
        if (resumeFile != null) {
            // 删除物理文件
            try {
                Files.deleteIfExists(Paths.get(resumeFile.getFilePath()));
            } catch (IOException e) {
                // 记录日志但不抛出异常
                System.err.println("删除文件失败: " + e.getMessage());
            }
            // 删除数据库记录
            resumeFileMapper.deleteById(id);
        }
    }

    @Override
    public byte[] downloadResume(Long id) throws Exception {
        ResumeFile resumeFile = getById(id);
        if (resumeFile == null) {
            throw new Exception("简历文件不存在");
        }
        
        Path filePath = Paths.get(resumeFile.getFilePath());
        if (!Files.exists(filePath)) {
            throw new Exception("文件不存在");
        }
        
        return Files.readAllBytes(filePath);
    }
}